import 'dart:io';

import 'package:cher_flare/config/url_api.dart';
import 'package:cher_flare/http/http_utils.dart';
import 'package:cher_flare/modules/login/models/ly_login_info_manager.dart';
import 'package:cher_flare/utils/app_color.dart';
import 'package:cher_flare/utils/ly_use_log_manager.dart';
import 'package:cher_flare/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

import '../../login/models/ly_login_model.dart';
import '../models/ly_goods_model.dart';
import '../models/ly_in_app_purchase_manager.dart';
import '../models/ly_order_model.dart';

class LYCoinShopPage extends StatefulWidget {
  const LYCoinShopPage({super.key});

  @override
  State<LYCoinShopPage> createState() => _LYCoinShopPageState();
}

class _LYCoinShopPageState extends State<LYCoinShopPage> {
  List<LyGoodsModel> dataList = [];
  @override
  void initState() {
    super.initState();
    LYUseLogManager.stat(page: LYLogPages.purchase);
    _requestGoodsList();
    LYInAppPurchaseManager.share.init();
  }

  @override
  void dispose() {
    LYInAppPurchaseManager.share.dispose();
    super.dispose();
  }

  void _requestGoodsList() async {
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    Map<String, dynamic> parameters = {
      'isIncludeSubscription': false,
      'payChannel': 'IAP'
    };
    final response = await HttpUtils.getInstance
        .post(URLApi.coinGoodsSearch, data: parameters);
    if (response.isSuccess && response.data is List) {
      for (final json in response.data) {
        final model = LyGoodsModel.fromJson(json);
        dataList.add(model);
      }
    }
    setState(() {});
    EasyLoading.dismiss();
  }

  void _createOrder(LyGoodsModel model) async {
    EasyLoading.show(maskType: EasyLoadingMaskType.black);
    LYUseLogManager.stat(page: LYLogPages.createOrder);
    Map<String, dynamic> parameters = {
      'entry': '',
      'source': '',
      'payChannel': 'IAP',
      'goodsCode': model.code
    };
    final response = await HttpUtils.getInstance
        .post(URLApi.rechargeCreate, data: parameters);
    if (response.isSuccess) {
      LYOrderModel orderModel = LYOrderModel.fromJson(response.data);
      final result = await LYInAppPurchaseManager.share
          .applePay({model.code ?? ''}, orderNo: orderModel.orderNo);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Utils.commonAppBar(title: 'Coin Shop', centerTitle: true),
      backgroundColor: AppColors.colorF8FDEE,
      body: Container(
        decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage('assets/images/login_bg_img.png'),
                fit: BoxFit.fill)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              margin: const EdgeInsets.only(
                  top: 20, left: 16, right: 16, bottom: 22),
              padding: const EdgeInsets.only(left: 51),
              height: 128,
              decoration: const BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('assets/images/my_coin_bg_img.png'),
                      fit: BoxFit.cover)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Image.asset(
                    'assets/images/cher_flare_coin_80_icon.png',
                    width: 80,
                    height: 80,
                  ),
                  Expanded(
                      child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        'My Coins',
                        style: TextStyle(
                            color: AppColors.color3A8927, fontSize: 16),
                      ),
                      const SizedBox(
                        height: 5,
                      ),
                      Text(
                        "${LYLoginInfoManager.getInstance.loginModel?.userInfo?.availableCoins ?? 0}",
                        style: const TextStyle(
                            color: AppColors.color3A8927,
                            fontSize: 26,
                            fontWeight: FontWeight.bold),
                      ),
                    ],
                  )),
                ],
              ),
            ),
            Expanded(child: _makeGoodsListWidget()),
          ],
        ),
      ),
    );
  }

  Widget _makeGoodsListWidget() {
    return GridView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisExtent: 91,
          crossAxisSpacing: 10,
          mainAxisSpacing: 20),
      itemBuilder: (ctx, index) {
        final model = dataList[index];
        return _makeGoodsItem(model, index);
      },
      itemCount: dataList.length,
    );
  }

  Widget _makeGoodsItem(LyGoodsModel model, int index) {
    debugPrint('=======${model.type}=${model.tags}');
    final tag = model.tags ?? '';
    final isShowOriginalPrice =
        model.price?.toDouble() != model.originalPrice?.toDouble();
    final discount = model.discount ?? 0;
    return InkWell(
      onTap: () => _createOrder(model),
      child: Container(
        height: 91,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: AppColors.whiteColor,
          boxShadow: [
            BoxShadow(
                color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.08),
                offset: const Offset(0, 2),
                blurRadius: 8)
          ],
        ),
        clipBehavior: Clip.hardEdge,
        child: Stack(
          children: [
            Positioned(
                top: 0,
                left: 0,
                right: 0,
                height: 70,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const SizedBox(
                      width: 18,
                    ),
                    Image.asset(
                      'assets/images/cher_flare_coin_50_icon.png',
                      width: 50,
                      height: 50,
                    ),
                    const SizedBox(
                      width: 12,
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '${model.exchangeCoin ?? 0}',
                          style: const TextStyle(
                              fontSize: 20,
                              color: AppColors.color202020,
                              fontWeight: FontWeight.bold),
                        ),
                        Visibility(
                          visible: discount > 0,
                          child: const SizedBox(
                            height: 6,
                          ),
                        ),
                        Visibility(
                          visible: discount > 0,
                          child: Text(
                            '${(discount * 100).toInt()}% off',
                            style: const TextStyle(
                              fontSize: 9,
                              color: Color(0xffff3ec8),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                )),
            Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                top: 70,
                child: Container(
                  color: AppColors.colorC7F4AC,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text("\$${model.price ?? 0}",
                          style: const TextStyle(
                              fontSize: 14,
                              color: AppColors.color39910F,
                              fontWeight: FontWeight.bold)),
                      Visibility(
                        visible: isShowOriginalPrice,
                        child: const SizedBox(
                          width: 9,
                        ),
                      ),
                      Visibility(
                        visible: isShowOriginalPrice,
                        child: Text("\$${model.originalPrice ?? 0}",
                            style: TextStyle(
                              decoration: TextDecoration.lineThrough,
                              fontSize: 10,
                              color: colorWithRGBA(r: 0, g: 0, b: 0, a: 0.3),
                            )),
                      ),
                      const SizedBox(
                        width: 9,
                      ),
                    ],
                  ),
                )),
            Positioned(
                top: 0,
                right: 0,
                child: Visibility(
                  visible: tag.isNotEmpty,
                  child: tag == "Hot"
                      ? _makeHotTagWidget(tag)
                      : _makeNormalTagWidget(tag),
                )),
          ],
        ),
      ),
    );
  }

  Widget _makeHotTagWidget(String tag) {
    return Container(
      height: 20,
      padding: const EdgeInsets.only(left: 5, right: 5),
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.only(
            topRight: Radius.circular(8), bottomLeft: Radius.circular(8)),
        color: Color(0xffffb18f),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(
            'assets/images/hot_icon.png',
            width: 10,
            height: 12,
          ),
          const SizedBox(
            width: 4,
          ),
          Text(
            tag,
            style: const TextStyle(color: AppColors.whiteColor, fontSize: 12),
          ),
        ],
      ),
    );
  }

  Widget _makeNormalTagWidget(String tag) {
    return Container(
      height: 20,
      padding: const EdgeInsets.only(left: 5, right: 5),
      alignment: Alignment.center,
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.only(
              topRight: Radius.circular(8), bottomLeft: Radius.circular(8)),
          gradient: LinearGradient(
              colors: [AppColors.colorCCFF78, AppColors.color78FF85],
              begin: Alignment.centerRight,
              end: Alignment.centerLeft)),
      child: Text(
        tag,
        style: const TextStyle(color: AppColors.whiteColor, fontSize: 12),
      ),
    );
  }
}
